package org.artifact.core.plugin.rpc.registry.zookeeper;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.I0Itec.zkclient.ZkClient;
import org.artifact.core.plugin.rpc.registry.ServiceRegistry;
import org.artifact.core.plugin.zookeeper.ZooKeeperPlugin;
import org.artifact.core.server.ServerPlugins;

/**
 * 基于 ZooKeeper 的服务注册接口实现
 *
 * @author huangyong
 * @since 1.0.0
 */
public class ZooKeeperServiceRegistry implements ServiceRegistry {

    private static final Log log = LogFactory.get(ZooKeeperServiceRegistry.class);

    @Override
    public void register(String serviceName, String serviceAddress) {
    	ZkClient zkClient = ServerPlugins.me().getPlugin(ZooKeeperPlugin.class).getClient();
        // 创建 registry 节点（持久）
        String registryPath = Constant.ZK_REGISTRY_PATH;
        if (!zkClient.exists(registryPath)) {
            zkClient.createPersistent(registryPath);
            log.debug("create registry node: {}", registryPath);
        }
        // 创建 service 节点（持久）
        String servicePath = registryPath + "/" + serviceName;
        if (!zkClient.exists(servicePath)) {
            zkClient.createPersistent(servicePath);
            log.debug("create service node: {}", servicePath);
        }
        // 创建 address 节点（临时）
        String addressPath = servicePath + "/address-";
        String addressNode = zkClient.createEphemeralSequential(addressPath, serviceAddress);
        log.debug("create address node: {}", addressNode);
    }
}